package com.sgj.gulimall.order.web;

import com.sgj.common.enums.BizCodeEnum;
import com.sgj.gulimall.order.service.OrderService;
import com.sgj.common.vo.OrderConfirmVo;
import com.sgj.gulimall.order.vo.OrderSubmitVo;
import com.sgj.gulimall.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/23 9:36
 */
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    /**
     * 带数据跳转结算页面
     * @param model
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo vo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", vo);
        // 展示订单确认的数据
        return "confirm";
    }

    /**
     * 提交下单
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {
        SubmitOrderResponseVo responseVo = orderService.submitOrder(vo);
        if (BizCodeEnum.ORDER_PASS.getCode().equals(responseVo.getCode())) {
            // 下单成功，进入支付页面
            model.addAttribute("submitOrderResp", responseVo);
            return "pay";
        } else {
            String msg = null;
            if (BizCodeEnum.TOKEN_VAILD_EXCEPTION.getCode().equals(responseVo.getCode())) {
                msg = "下单失败:订单信息过期，请刷新再次提交";
            }
            if (BizCodeEnum.NO_STOCK_EXCEPTION.getCode().equals(responseVo.getCode())) {
                msg = "下单失败:商品库存不足";
            }
            // 下单失败返回订单页面
            redirectAttributes.addFlashAttribute("msg", msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}